<template>
  <a-card style="overflow: auto">
    <!--    基础信息开始-->
    <div>
      <h1 class="titleZ">基础信息</h1>
      <a-row v-if="pageType==='add'||pageType==='copy'" class="row">
        <a-col :span="4" class="rowLabel">品牌</a-col>
        <a-col :span="10">
          <a-select v-model:value="formData.baseData.brandId" allowClear placeholder="选择品牌" style="width: 160px"
                    @change="queryModel">
            <a-select-option v-for="option in brandOptions" :value="option.id">{{ option.brandName }}</a-select-option>
          </a-select>
        </a-col>
      </a-row>
      <a-row v-if="pageType==='add'||pageType==='copy'" class="row">
        <a-col :span="4" class="rowLabel">品类</a-col>
        <a-col :span="10">
          <a-select v-model:value="formData.baseData.category" allowClear placeholder="选择品类" style="width: 160px"
                    @change="queryModel">
            <a-select-option value="1">手机</a-select-option>
            <a-select-option value="2">平板</a-select-option>
          </a-select>
        </a-col>
      </a-row>
      <a-row class="row">
        <a-col :span="4" class="rowLabel"><span class="req">*</span>型号</a-col>
        <a-col :span="10">
          <a-select v-model:value="formData.baseData.modelId" :disabled="pageType!=='add'&&pageType!=='copy'"
                    :field-names="{label: 'modelName',value: 'id'}"
                    :filter-option="filterModelOption"
                    :options="modelOptions"
                    allowClear placeholder="选择型号" show-search style="width: 160px">
          </a-select>
        </a-col>
      </a-row>
      <a-row class="row">
        <a-col :span="4" class="rowLabel" style="align-self: flex-start">内部备注</a-col>
        <a-col :span="10">
          <a-textarea v-model:value="formData.baseData.bak" :maxlength="100" show-count/>
        </a-col>
      </a-row>

      <a-row class="row">
        <a-col :span="4" class="rowLabel"><span class="req">*</span>状态</a-col>
        <a-col :span="10">
          <a-radio-group v-model:value="formData.baseData.status" :disabled="pageType!=='edit'" name="radioGroup">
            <a-radio :value="0">下架</a-radio>
            <a-radio :value="1">上架</a-radio>
          </a-radio-group>
        </a-col>
      </a-row>
    </div>
    <a-divider></a-divider>
    <!--基础信息结束-->

    <!--    题目配置开始-->
    <div class="questionList">
      <h1 class="titleZ">题目配置</h1>
      <Draggable :force-fallback="true" :list="formData.questionList"
                 animation="300" ghost-class="ghost" handle=".draggableIcon">
        <template #item="{ element,index }">
          <div style="border: 1px solid #d9d9d9;border-radius: 2px;margin-bottom: 12px">
            <!--            题目-->
            <a-row class="aRow alignCenter">
              <a-col :span="14" class="alignCenter">
                <DragOutlined class="draggableIcon"/>
                <b>{{ index + 1 }}.{{ element.questionName }}</b>
                <span
                    style="margin: 0 14px">{{ element.selectType === 0 ? '单选' : '多选' }}</span>
                <span>{{ element.requiredFlag === 1 ? '必选' : '非必选' }}</span>
              </a-col>
              <a-col :span="5">
                <b>跳转设置</b>
              </a-col>
              <a-col :span="4">
                <b>价格设置</b>
              </a-col>
              <a-col :span="1">
                <DeleteOutlined style="float: right;margin-right: 8px;color: red"
                                @click="deleteQuestion(element.id,element.questionName)"/>
              </a-col>
            </a-row>

            <Draggable :force-fallback="true" :list="element.options"
                       animation="300" ghost-class="ghost" handle=".draggableIconOption">
              <template #item="{ element,index }">
                <div>
                  <!--            题目-->
                  <a-row class="aRow alignCenter">
                    <a-col :offset="1" :span="13" class="alignCenter">
                      <DragOutlined class="draggableIconOption"/>
                      <span>
                        <div>{{ element.optionName }}</div>
                        <div style="color: #999999">
                          <span>
                            {{ formatQuestionInfo('grade', element.grade) }}
                          </span>
                          <span style="margin: 0 8px">
                            {{ formatQuestionInfo('choosable', element.choosable) }}
                          </span>
                          <span v-if="element.choosable===0">：{{ element.reason }}</span>
                        </div>
                      </span>
                    </a-col>
                    <a-col :span="5">
                      <a-select v-model:value="element.jump" allowClear placeholder="跳转方式" style="width: 160px">
                        <!--                        <a-select-option value="jumpNot">不跳转</a-select-option>-->
                        <a-select-option value="jumpToNext">跳转到下一题</a-select-option>
                        <a-select-option value="jumpToEnd">跳转到结束</a-select-option>
                      </a-select>
                    </a-col>
                    <a-col :span="4">
                      <a-input-number v-model:value="element.price.value" addon-after="RMB" min="0"
                                      style="width: 180px">
                        <template #addonBefore>
                          <a-select v-model:value="element.price.type" style="width: 60px">
                            <a-select-option value="plus">+</a-select-option>
                            <a-select-option value="minus">-</a-select-option>
                          </a-select>
                        </template>
                      </a-input-number>
                    </a-col>
                  </a-row>

                </div>
              </template>
            </Draggable>

          </div>
        </template>
      </Draggable>
      <div class="showAddQuestionBtn">
        <span @click="addQuestion">
        <PlusOutlined/>添加题目
        </span>
      </div>
    </div>
    <a-divider></a-divider>

    <div>
      <h1 class="titleZ">多选价格规则<span
          style="font-size: 14px;color: #999999;font-weight: normal">(没有添加多选题目时可不填)</span></h1>
      2个多选时：多选结果=(两个选项价格之和)*
      <a-input-number v-model:value="multipleRule.two" addon-after="%" min="0"
                      style="width: 130px">
      </a-input-number>
      <br>
      3个及以上多选时：多选结果=最小的选项价格+(其余选项价格之和)*
      <a-input-number v-model:value="multipleRule.more" addon-after="%" min="0"
                      style="width: 130px">
      </a-input-number>
    </div>
    <a-divider></a-divider>
    <!--    题目配置结束-->

    <!--    基准价配置开始-->
    <div>
      <h1 class="titleZ">基准价配置</h1>

      <a-row class="row">
        <a-col :span="4" class="rowLabel">基准题目1</a-col>
        <a-col :span="10">
          <a-select v-model:value="formData.basePrice.baseQuestionFirstId"
                    :field-names="{label:'questionName',value: 'id'}"
                    :options="availableFirstQuestionOptions"
                    allowClear placeholder="选择题目" style="width: 160px"
                    @change="baseQuestionSelectedChange('second')">
          </a-select>
        </a-col>
      </a-row>
      <a-row class="row">
        <a-col :span="4" class="rowLabel">基准题目2</a-col>
        <a-col :span="10">
          <a-select v-model:value="formData.basePrice.baseQuestionSecondId"
                    :field-names="{label:'questionName',value: 'id'}"
                    :options="availableSecondQuestionOptions"
                    allowClear placeholder="选择题目" style="width: 160px"
                    @change="baseQuestionSelectedChange('first')">
          </a-select>
        </a-col>
      </a-row>
      <!--      基准价表格-->
      <div style="margin-bottom: 8px">
        <a-button type="primary" @click="showFillModal">批量填充</a-button>
      </div>
      <a-table :columns="basePriceTableColumns" :pagination="false"
               :data-source="formData.basePrice.tableData" bordered>
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex === 'A'">
            <a-input-number v-model:value="record.priceA" addon-after="RMB" min="0"
                            style="width: 130px">
            </a-input-number>
          </template>
          <template v-if="column.dataIndex === 'B'">
            <a-input-number v-model:value="record.priceB" addon-after="RMB" min="0"
                            style="width: 130px">
            </a-input-number>
          </template>
          <template v-if="column.dataIndex === 'C'">
            <a-input-number v-model:value="record.priceC" addon-after="RMB" min="0"
                            style="width: 130px">
            </a-input-number>
          </template>
          <template v-if="column.dataIndex === 'D'">
            <a-input-number v-model:value="record.priceD" addon-after="RMB" min="0"
                            style="width: 130px">
            </a-input-number>
          </template>
          <template v-if="column.dataIndex === 'S'">
            <a-input-number v-model:value="record.priceS" addon-after="RMB" min="0"
                            style="width: 130px">
            </a-input-number>
          </template>
          <template v-if="column.dataIndex === 'floorPrice'">
            <a-input-number v-model:value="record.priceFloor" addon-after="RMB" min="0"
                            style="width: 130px">
            </a-input-number>
          </template>
        </template>
      </a-table>
    </div>
    <a-divider></a-divider>
    <!--    基准价配置结束-->

    <div style="text-align: right">
      <a-button style="margin-right: 24px" @click="cancel">取消</a-button>
      <a-button type="primary" @click="save">保存</a-button>
    </div>

  </a-card>

  <!--  添加和修改对话框-->
  <a-modal :visible="addQuestionModal.addQuestionModalVisible" title="添加题目" width="800px"
           @cancel="onAddQuestionClose" @ok="handleAddQuestionOk">

    <a-row class="row">
      <a-col :span="4" class="rowLabel">分类标签</a-col>
      <a-col :span="20">
        <a-select v-model:value="addQuestionModal.conditionTags" :options="addQuestionModal.conditionTagsOptions"
                  allowClear
                  placeholder="选择标签" style="width: 160px;margin-right: 12px" @change="conditionTagsChange">
        </a-select>
        (用于筛选下方题目)
      </a-col>
    </a-row>
    <a-row class="row">
      <a-col :span="4" class="rowLabel">题目</a-col>
      <a-col :span="16">
        <a-select v-model:value="addQuestionModal.selectedQuestionId" :field-names="{label: 'questionName',value: 'id'}"
                  :filter-option="filterModelOption"
                  :options="addQuestionModal.questionOptions"
                  allowClear
                  placeholder="选择题目" show-search style="width: 160px" @change="questionSelectedChange">
        </a-select>
        <span v-if="addQuestionModal.selectedQuestionId"
              style="margin: 0 14px">
          {{ formatQuestionInfo('selectType', addQuestionModal.selectedQuestionDetail?.selectType) }}
        </span>
        <span v-if="addQuestionModal.selectedQuestionId">
          {{ formatQuestionInfo('requiredFlag', addQuestionModal.selectedQuestionDetail?.requiredFlag) }}</span>
      </a-col>
      <a-col v-if="addQuestionModal.selectedQuestionId" :span="4">
        <a-button type="link" @click="openNewPageForQuestion">设置</a-button>
        <a-button type="link" @click="conditionTagsChange">刷新</a-button>
      </a-col>
    </a-row>
    <div v-if="addQuestionModal.selectedQuestionDetail">
      <a-row class="row">
        <a-col :span="4" class="rowLabel">选项</a-col>
        <a-col :span="20">
          <a-checkbox
              v-model:checked="addQuestionModal.selectAllOptionState"
              :indeterminate="addQuestionModal.selectAllOptionIndeterminate"
              @change="onCheckAllOptionChange"
          >全选
          </a-checkbox>
        </a-col>
      </a-row>
      <a-row class="row">
        <a-col :span="4" class="rowLabel"></a-col>
        <a-col :span="20">
          <a-checkbox-group v-model:value="addQuestionModal.selectedOptions" style="width: 100%">
            <div v-for="option in addQuestionModal.selectedQuestionDetail.options">
              <a-checkbox :value="option.id">{{ option.optionName }}</a-checkbox>
              <span style="color: #999999">
              {{ formatQuestionInfo('choosable', option.choosable) }}
              <span v-if="option.choosable===0">：{{ option.reason }}</span>
              </span>
            </div>
          </a-checkbox-group>
        </a-col>
      </a-row>
    </div>

  </a-modal>

  <!--  填充对话框-->
  <a-modal :visible="fillModal.visible" title="快速填充" width="600px"
           @cancel="hideFillModal" @ok="fillPrice">

    <a-row class="row">
      <a-col :span="24">
        <a-select v-model:value="fillModal.sourceId"
                  allowClear @change="previewFillPrice"
                  placeholder="请选择要参考的列" style="width: 160px;margin-right: 12px">
          <a-select-option value="priceA">A</a-select-option>
          <a-select-option value="priceB">B</a-select-option>
          <a-select-option value="priceC">C</a-select-option>
          <a-select-option value="priceD">D</a-select-option>
          <a-select-option value="priceS">S</a-select-option>
          <a-select-option value="priceFloor">保底价格</a-select-option>
        </a-select>
        <a-select v-model:value="fillModal.resultId"
                  allowClear @change="previewFillPrice"
                  placeholder="请选择要填充的列" style="width: 160px;margin-right: 12px">
          <a-select-option value="priceA">A</a-select-option>
          <a-select-option value="priceB">B</a-select-option>
          <a-select-option value="priceC">C</a-select-option>
          <a-select-option value="priceD">D</a-select-option>
          <a-select-option value="priceS">S</a-select-option>
          <a-select-option value="priceFloor">保底价格</a-select-option>
        </a-select>
        <a-input-number @change="previewFillPrice" v-model:value="fillModal.num"
                        :addon-after="fillModal.rule==='times'?'%':'RMB'" min="0"
                        style="width: 180px">
          <template #addonBefore>
            <a-select @change="previewFillPrice" v-model:value="fillModal.rule" style="width: 60px">
              <a-select-option value="plus">+</a-select-option>
              <a-select-option value="minus">-</a-select-option>
              <a-select-option value="times">×</a-select-option>
            </a-select>
          </template>
        </a-input-number>
      </a-col>
    </a-row>

    <a-table :columns="previewFillTableColumns" :pagination="false"
             :data-source="fillModal.previewList" bordered>

    </a-table>
  </a-modal>
</template>

<script setup>

import {onMounted, reactive, ref, watch} from "vue";
import {brandApi} from "/@/views/business/data-config/brand/brand-api";
import {modelApi} from "/@/views/business/data-config/model/model-api";
import {questionApi, formatQuestionInfo} from "/@/views/business/evaluate/question/question-api";
import {smartSentry} from "/@/lib/smart-sentry";
import {message, Modal} from "ant-design-vue";
import Draggable from "vuedraggable";
import _ from 'lodash';
import {modelEvaluateApi} from "/@/views/business/evaluate/model-evaluate/model-evaluate";
import {useRoute} from "vue-router";

const pageType = ref('add');
const route = useRoute();
let brandOptions = ref([]);
let modelOptions = ref([]);
let availableFirstQuestionOptions = ref([]);
let availableSecondQuestionOptions = ref([]);
const formData = reactive({
  baseData: {
    id: undefined,// 估价模版id
    brandId: undefined,// 品牌
    category: undefined,// 品类
    modelId: undefined,// 型号
    status: 0,// 状态
    bak: undefined,// 内部备注
  },
  questionList: [],// 题目配置列表
  basePrice: {
    baseQuestionFirstId: undefined,
    baseQuestionSecondId: undefined,
    tableData: [],
  }
});

const addQuestionModalDefault = {
  addQuestionModalVisible: false,
  conditionTagsOptions: [
    {label: '通用', value: '0'},
    {label: 'iPhone', value: '1'},
    {label: 'iPad', value: '2'},
    {label: '安卓手机', value: '3'}], // 分类标签可选项
  conditionTags: undefined, // 分类标签 作为过滤条件
  questionOptions: [],// 可选题目
  options: [],// 选项
  selectedQuestionId: undefined, //选中的题目id
  selectedQuestionDetail: undefined, //根据选中的题目id查询到的详情
  selectedOptions: [], //选中的选项
  selectAllOptionState: false,//选项全选状态
  selectAllOptionIndeterminate: false,//全选模糊状态
};
const previewFillTableColumns = [
  {
    align: 'center',
    title: '选项',
    dataIndex: 'name',
    width: 160,
    ellipsis: true,
  },
  {
    align: 'center',
    title: '参考价格',
    dataIndex: 'sourcePrice',
    width: 100,
  },
  {
    align: 'center',
    title: '填充价格',
    dataIndex: 'resultPrice',
    width: 100,
  },
]
const fillModalDefault = {
  visible: false,
  tableList: [],
  sourceId: undefined,
  resultId: undefined,
  previewList: [],
  num: 0,
  rule: 'plus', // minus plus times
};
let fillModal = reactive({...fillModalDefault});
let addQuestionModal = reactive({...addQuestionModalDefault});

// 基准价配置表格列
const basePriceTableColumns = ref([]);
// 多选价格规则
const multipleRule = reactive({
  two: undefined,
  more: undefined,
});

onMounted(async () => {
  queryBrand();
  queryModel();
  pageType.value = route.query?.pageType;
  if (route.query?.modelEvaluateId) {
    const {data} = await modelEvaluateApi.detail(route.query?.modelEvaluateId);
    formData.baseData.id = pageType.value === 'copy' ? undefined : route.query?.modelEvaluateId;
    formData.baseData.modelId = data.modelId;
    formData.baseData.bak = data.bak;
    formData.baseData.status = data.status;
    const priceList = [];
    const context = JSON.parse(data.context);
    for (let [k, v] of Object.entries(context.questionPriceForKey)) {
      const [questionId, optionId] = k.split('-');
      priceList.push({questionId: questionId * 1, optionId: optionId * 1, price: v});
    }
    multipleRule.two = context?.multipleRule?.two || undefined;
    multipleRule.more = context?.multipleRule?.more || undefined;
    const questionContext = JSON.parse(data.questionContext);
    console.log(context);
    formData.questionList = questionContext.map(q => {
      q.options.forEach(o => {
        priceList.forEach(price => {
          if (price.questionId === q.id && price.optionId === o.id) {
            o.price = price.price;
          }
        })
      })
      return q;
    });
    console.log(formData.questionList);
    formData.basePrice.baseQuestionFirstId = context.basePrice.baseQuestionFirstId;
    formData.basePrice.baseQuestionSecondId = context.basePrice.baseQuestionSecondId;
    generateTableColumns();
    getAvailableQuestionOptions('first');
    getAvailableQuestionOptions('second');
    formData.basePrice.tableData = context.basePrice.tableData;
  }
});

// 查询品牌
async function queryBrand() {
  try {
    let responseModel = await brandApi.queryPage({pageNum: 1, pageSize: 200});
    brandOptions.value = responseModel.data.list;
  } catch (e) {
    smartSentry.captureError(e);
  }
}

// 查询型号
async function queryModel() {
  try {
    let responseModel = await modelApi.queryPage({
      brandId: formData.baseData.brandId,
      category: formData.baseData.category,
      pageNum: 1, pageSize: 200
    });
    modelOptions.value = responseModel.data.list;
  } catch (e) {
    smartSentry.captureError(e);
  }
}

// 添加题目
function addQuestion() {
  addQuestionModal.addQuestionModalVisible = true;
  conditionTagsChange();
  console.log(addQuestionModal);
}

// 标签改变，重新查询题目
async function conditionTagsChange() {
  let responseModel = await questionApi.queryPage({
    questionTag: addQuestionModal.conditionTags,
    pageNum: 1,
    pageSize: 200,
  });
  addQuestionModal.questionOptions = responseModel.data.list;
  questionSelectedChange();
}

//打开新的页面编辑题目
function openNewPageForQuestion() {
  window.open(`/#/question-config?questionId=${addQuestionModal.selectedQuestionId}&isCopy=false`, 'blank')
}

//添加题目到列表中
function handleAddQuestionOk() {
  let existMultiple = false;
  if (!addQuestionModal.selectedQuestionId) {
    return message.error('没有选择题目');
  }
  if (!addQuestionModal.selectedOptions.length) {
    return message.error('请选择题目的选项');
  }
  formData.questionList.forEach(q => {
    if (addQuestionModal.selectedQuestionDetail.selectType === 1 && q.selectType === 1) {
      existMultiple = true;
    }
  })
  if (existMultiple) {
    return message.error('多选题目只能添加一个');
  }
  if (formData.questionList.findIndex(item => item.id === addQuestionModal.selectedQuestionId) !== -1) {

    return message.error('该题目已添加,请勿重复添加');
  }

  const question = _.cloneDeep(addQuestionModal.selectedQuestionDetail);
  question.options = question.options.map(item => {
    return {...item, jump: 'jumpToNext', price: {value: 0, type: 'minus'}};
  })
  formData.questionList.push({
    id: question.id,
    questionName: question.questionName,
    requiredFlag: question.requiredFlag,
    selectType: question.selectType,
    options: question.options.filter(item => (addQuestionModal.selectedOptions.findIndex(id => id === item.id) !== -1)),
  });
  formData.questionList =
      [...formData.questionList.filter(item => item.selectType === 0),
        ...formData.questionList.filter(item => item.selectType === 1)];
  console.log(formData.questionList)
  getAvailableQuestionOptions('first');
  getAvailableQuestionOptions('second');
  onAddQuestionClose();
}

function onAddQuestionClose() {
  Object.assign(addQuestionModal, addQuestionModalDefault);
}

// 取消
function cancel() {
  window.history.back();
}

// 保存
async function save() {
  const formDataClone = _.cloneDeep(formData);
  let existMultiple = false;
  if (!formDataClone.baseData.modelId) {
    return message.error('请选择型号');
  }
  if (!formDataClone.questionList.length) {
    return message.error('请添加题目');
  }
  formData.questionList.forEach(q => {
    if (q.selectType === 1) {
      existMultiple = true;
    }
  })
  if (existMultiple && (multipleRule.two === '' || multipleRule.two === undefined || multipleRule.two === null)) {
    return message.error('请输入选中两个多选时的价格规则');
  }
  if (existMultiple && (multipleRule.more === '' || multipleRule.more === undefined || multipleRule.more === null)) {
    return message.error('请输入选中三个及以上多选时的价格规则');
  }
  if (!formDataClone.basePrice.baseQuestionFirstId) {
    return message.error('请选择基准题目1');
  }
  if (!formDataClone.basePrice.baseQuestionSecondId) {
    return message.error('请选择基准题目2');
  }
  if (!formDataClone.basePrice.tableData.length) {
    return message.error('没有正确生成表格数据');
  }
  let basePriceTableVerify = false;
  formDataClone.basePrice.tableData.forEach(item => {
    if (item.priceA === '' || item.priceA === undefined || item.priceA === null) {
      basePriceTableVerify = true;
      message.error(`请输入(${item.firstOptionName}-${item.secondOptionName})的A成色价格`)
    }
    if (item.priceB === '' || item.priceB === undefined || item.priceB === null) {
      basePriceTableVerify = true;
      message.error(`请输入(${item.firstOptionName}-${item.secondOptionName})的B成色价格`)
    }
    if (item.priceC === '' || item.priceC === undefined || item.priceC === null) {
      basePriceTableVerify = true;
      message.error(`请输入(${item.firstOptionName}-${item.secondOptionName})的C成色价格`)
    }
    if (item.priceD === '' || item.priceD === undefined || item.priceD === null) {
      basePriceTableVerify = true;
      message.error(`请输入(${item.firstOptionName}-${item.secondOptionName})的D成色价格`)
    }
    if (item.priceS === '' || item.priceS === undefined || item.priceS === null) {
      basePriceTableVerify = true;
      message.error(`请输入(${item.firstOptionName}-${item.secondOptionName})的S(准新)成色价格`)
    }
    if (item.priceFloor === '' || item.priceFloor === undefined || item.priceFloor === null) {
      basePriceTableVerify = true;
      message.error(`请输入(${item.firstOptionName}-${item.secondOptionName})的保底价格`)
    }
  })
  if (basePriceTableVerify) {
    return;
  }
  try {
    const problemId = [];
    const optionId = [];
    formDataClone.questionList.forEach(q => {
      problemId.push(q.id);
      q.options.forEach(o => {
        optionId.push(o.id);
      });
    });
    let newPrice = 0;
    let usedPrice = 0;
    formDataClone.basePrice.tableData.forEach(t => {
      newPrice = t.priceS > newPrice ? t.priceS : newPrice;
      usedPrice = t.priceA > usedPrice ? t.priceA : usedPrice;
      usedPrice = t.priceB > usedPrice ? t.priceB : usedPrice;
      usedPrice = t.priceC > usedPrice ? t.priceC : usedPrice;
      usedPrice = t.priceD > usedPrice ? t.priceD : usedPrice;
      usedPrice = t.priceFloor > usedPrice ? t.priceFloor : usedPrice;
    });

    let questionContext = [];
    let questionPriceForKey = {};
    formDataClone.questionList.forEach(q => {
      questionContext.push({
        id: q.id,
        options: q.options.map((o, index) => {
          questionPriceForKey[`${q.id}-${o.id}`] = o.price;
          delete o.price;
          return {id: o.id, jump: o.jump};
        })
      });
    });

    let basePriceForKey = {};
    formDataClone.basePrice.tableData.forEach(item => {
      basePriceForKey[`${item.firstOptionId}-${item.secondOptionId}`] = item;
    });
    const requestData = {
      id: formDataClone.baseData.id,
      bak: formDataClone.baseData.bak,
      status: formDataClone.baseData.status,
      modelId: formDataClone.baseData.modelId,
      newPrice,//准新价格最大值
      usedPrice,//二手价格最大值
      problemId: problemId.join(','),//所有问题的id
      optionId: optionId.join(','),//所有选项的id
      questionContext: JSON.stringify(questionContext),
      context: JSON.stringify({
        basePrice: formDataClone.basePrice,
        basePriceForKey,
        questionPriceForKey,
        multipleRule: multipleRule.two !== '' && multipleRule.two !== null && multipleRule.two !== undefined ? multipleRule : {}
      }),
    };
    if (requestData.id) {
      await modelEvaluateApi.update(requestData);
    } else {
      await modelEvaluateApi.add(requestData);
    }
    let successMsg = '';
    switch (pageType.value) {
      case 'copy':
        successMsg = '复制';
        break;
      case 'edit':
        successMsg = '编辑';
        break;
      case 'add':
        successMsg = '添加';
        break;
    }
    message.success(`${successMsg}成功`);
    window.history.back();
  } catch (e) {
    smartSentry.captureError(e);
  }
}

function deleteQuestion(id, name) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除【' + name + '】吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      formData.questionList = formData.questionList.filter(item => item.id !== id);
      if (formData.basePrice.baseQuestionFirstId === id || formData.basePrice.baseQuestionSecondId === id) {
        formData.basePrice.baseQuestionFirstId = formData.basePrice.baseQuestionFirstId === id ? undefined : formData.basePrice.baseQuestionFirstId;
        formData.basePrice.baseQuestionSecondId = formData.basePrice.baseQuestionSecondId === id ? undefined : formData.basePrice.baseQuestionSecondId;
        baseQuestionSelectedChange('first');
        baseQuestionSelectedChange('second');
      }
    },
    cancelText: '取消',
    onCancel() {
      return Promise.resolve();
    },
  });
}

// 输入过滤型号
function filterModelOption(input, option) {
  return option.modelName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
}

// 选中的题目发生变化
async function questionSelectedChange() {
  clearSelectionOption();
  if (!addQuestionModal.selectedQuestionId) {
    addQuestionModal.selectedQuestionDetail = undefined;
    addQuestionModal.selectAllOptionState = false;
    return;
  }
  const {data} = await questionApi.detail(addQuestionModal.selectedQuestionId);
  addQuestionModal.selectedQuestionDetail = data;
  console.log(data);
}

// 清空选中的选项
function clearSelectionOption() {
  addQuestionModal.selectedQuestionDetail = undefined;
  addQuestionModal.selectedOptions = [];
  addQuestionModal.selectAllOptionState = false;
  addQuestionModal.selectAllOptionIndeterminate = false;
}

function onCheckAllOptionChange(e) {
  addQuestionModal.selectedOptions = e.target.checked ? addQuestionModal.selectedQuestionDetail?.options.map((item) => item.id) : [];
  addQuestionModal.selectAllOptionIndeterminate = false;
}

function baseQuestionSelectedChange(source) {
  getAvailableQuestionOptions(source);
  generateTableColumns();
}

function getAvailableQuestionOptions(source) {
  const cloneQuestionList = _.cloneDeep(formData.questionList);
  if (!formData.questionList.length) {
    availableFirstQuestionOptions.value = [];
    availableSecondQuestionOptions.value = [];
    return;
  }
  if (source === 'first') {
    availableFirstQuestionOptions.value = cloneQuestionList.map(item => {
      item.disabled = false;
      if (item.id === formData.basePrice.baseQuestionSecondId) {
        item.disabled = true;
      }
      delete item.options;
      return item;
    });
    console.log(availableFirstQuestionOptions)
  }
  if (source === 'second') {
    availableSecondQuestionOptions.value = cloneQuestionList.map(item => {
      item.disabled = false;
      if (item.id === formData.basePrice.baseQuestionFirstId) {
        item.disabled = true;
      }
      delete item.options;
      return item;
    })
  }

}

// 生成表格格式
function generateTableColumns() {
  let firstDetail = {};
  let secondDetail = {};
  setTableData();
  if (!formData.basePrice.baseQuestionSecondId || !formData.basePrice.baseQuestionFirstId) {
    basePriceTableColumns.value = [];
    return;
  }
  formData.questionList.forEach(item => {
    if (item.id === formData.basePrice.baseQuestionFirstId) {
      firstDetail = item;
    }
    if (item.id === formData.basePrice.baseQuestionSecondId) {
      secondDetail = item;
    }
  });
  basePriceTableColumns.value = [
    {
      title: firstDetail.questionName,
      dataIndex: 'firstOptionName',
      width: 180,
      ellipsis: true,
      customCell: (_, index) => {
        let v = {rowSpan: 0};
        for (let i = 0; i < firstDetail.options.length; i++) {
          if (index === i * secondDetail.options.length) {
            v = {rowSpan: secondDetail.options.length};
          }
        }
        return v;
      },
    },
    {
      title: secondDetail.questionName,
      dataIndex: 'secondOptionName',
      width: 180,
      ellipsis: true,
    },
    {
      title: 'A',
      dataIndex: 'A',
      width: 160,
    },
    {
      title: 'B',
      dataIndex: 'B',
      width: 160,
    },
    {
      title: 'C',
      dataIndex: 'C',
      width: 160,
    },
    {
      title: 'D',
      dataIndex: 'D',
      width: 160,
    },
    {
      title: 'S(准新价)',
      dataIndex: 'S',
      width: 160,
    },
    {
      title: '保底价格',
      dataIndex: 'floorPrice',
      width: 160,
    },
  ];
}

// 设置表格数据
function setTableData() {
  let firstDetail = {};
  let secondDetail = {};
  formData.basePrice.tableData = [];
  if (!formData.basePrice.baseQuestionSecondId || !formData.basePrice.baseQuestionFirstId) {
    formData.basePrice.tableData = [];
    return;
  }
  formData.questionList.forEach(item => {
    if (item.id === formData.basePrice.baseQuestionFirstId) {
      firstDetail = item;
    }
    if (item.id === formData.basePrice.baseQuestionSecondId) {
      secondDetail = item;
    }
  });
  firstDetail.options.forEach(first => {
    secondDetail.options.forEach(second => {
      formData.basePrice.tableData.push({
        firstOptionName: first.optionName,
        firstOptionId: first.id,
        secondOptionName: second.optionName,
        secondOptionId: second.id,
        priceA: '',
        priceB: '',
        priceC: '',
        priceD: '',
        priceS: '',
        priceFloor: '',
      })
    })
  })
}

// 显示批量填充模态框
function showFillModal() {
  fillModal.visible = true;
  console.log(formData.basePrice.tableData);
  fillModal.tableList = _.cloneDeep(formData.basePrice.tableData);
}

// 隐藏批量填充模态框
function hideFillModal() {
  Object.assign(fillModal, fillModalDefault);
}

// 填充到表格
function fillPrice() {
  if (!fillModal.sourceId) {
    return message.warn('请选择参考列');
  }
  if (!fillModal.resultId) {
    return message.warn('请选择要填充的列');
  }
  formData.basePrice.tableData.forEach(item => {
    fillModal.previewList.forEach(p => {
      if (p.firstOptionId === item.firstOptionId && p.secondOptionId === item.secondOptionId) {
        item[fillModal.resultId] = p.resultPrice;
      }
    })
  });
  hideFillModal();
}

function previewFillPrice() {
  if (!fillModal.sourceId ||
      fillModal.num === '' ||
      fillModal.num === null
      || fillModal.num === undefined) {
    fillModal.previewList = [];
    return;
  }
  const data = _.cloneDeep(fillModal.tableList);
  fillModal.previewList = data.map(item => {
    const r = {
      name: item.firstOptionName + ' ' + item.secondOptionName,
      firstOptionId: item.firstOptionId,
      secondOptionId: item.secondOptionId,
      sourcePrice: item[fillModal.sourceId],
      resultPrice: 0,
    }
    switch (fillModal.rule) {
      case 'plus':
        r.resultPrice = (r.sourcePrice + fillModal.num) | 0;
        break;
      case 'minus':
        r.resultPrice = (r.sourcePrice - fillModal.num) | 0;
        break;
      case 'times':
        r.resultPrice = (r.sourcePrice * fillModal.num / 100) | 0;
        break;
    }
    return r;
  });
}

watch(
    () => addQuestionModal.selectedOptions,
    val => {
      addQuestionModal.selectAllOptionIndeterminate = !!val.length && val.length < addQuestionModal.selectedQuestionDetail?.options.length;
      addQuestionModal.selectAllOptionState = val.length === addQuestionModal.selectedQuestionDetail?.options.length;
    },
);
</script>

<style lang="less" scoped>
.titleZ {
  font-size: 16px;
  font-weight: bold;
}

.row {
  margin-bottom: 8px;
  align-items: center;

  .rowLabel {
    text-align: right;
    padding-right: 8px;

    .req {
      color: red;
    }
  }
}

.showAddQuestionBtn {
  text-align: center;
  cursor: pointer;
  font-size: 16px;
  color: #00a0e9;
  font-weight: bold;
}

.questionList {
  .aRow {

  }
}

.draggableIcon {
  font-size: 28px;
  margin-right: 8px;
}

.draggableIconOption {
  margin-right: 8px;
}

.alignCenter {
  display: flex;
  flex-direction: row;
  align-items: center;
}
</style>